﻿#include "processlinuxwrap.h"
#include <QProcess>

bool ProcessLinuxWrap::getSpecifyProcessIsRun(QString ProcessName)
{
    qDebug()<< "init process of pid: "<< system("pidof init");
}

//V1.0.0
ProcessLinuxWrap::ErrCode ProcessLinuxWrap::getPid(QString ProcessName, pid_t *opPid)
{
#if 0 //system is not suit pidof order.
    int pid = system("pidof init");
    qDebug()<< "init process of pid: "<< pid;
    return pid;
#else //popen is suit pidof order.
    FILE *fp;
    char buf[100];
    char cmd[200]={'\0'};
    pid_t pid = 0;

    QString qstr("pidof ");
    qstr += ProcessName;

    fp = popen(qstr.toLocal8Bit().data(),"r");//match pclose()

    if(fp==NULL){
        return ErrCode::ErrOrderImplementFail;
    }

    if(fgets(buf,255,fp) == NULL){
        return ErrCode::ErrSpecifyNameOfProcessNoRun;
    }

    pid = atoi(buf);
    qDebug()<< "init process of pid: "<< pid;

    pclose(fp);//match popen()

    *opPid = pid;
    return ErrCode::ErrOK;
#endif
}

ProcessLinuxWrap::ErrCode ProcessLinuxWrap::createDetachedPid(QString AppPath)
{
    bool ret = QProcess::startDetached(AppPath);//启动一个进程，然后使其和当前进程脱离进程的父子关系。
    if(ret==true){
        return ErrCode::ErrOK;
    }else{
        return ErrCode::ErrCreateProcessFail;
    }
}

ProcessLinuxWrap::ErrCode ProcessLinuxWrap::killPid(pid_t Pid)
{
    int ret = kill(Pid,SIGKILL);
    if(ret==0){
        return ErrCode::ErrOK;
    }else{
        return ErrCode::ErrKillProcessFail;
    }
}

ProcessLinuxWrap::ProcessLinuxWrap(QObject *parent) : QObject(parent)
{

}
